package com.hmall.search.config.interceptor;


import com.hmall.search.mapper.ItemMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private ItemMapper itemMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("检测用户登录状态");
        String nameId = request.getHeader("authorization");
        if (StringUtils.isNotBlank(nameId)){
            String name = this.itemMapper.getName(Integer.valueOf(nameId));
            log.info("用户登录："+name);
            return true;
        }else {
            log.error("用户未登录");
            response.setStatus(401);
            request.setCharacterEncoding("UTF-8");
            response.getWriter().write("未登录");
            return false;
        }
    }

}
